package org.example.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import eu.bitwalker.useragentutils.UserAgent;
import org.example.system.entity.LoginLog;
import org.example.system.mapper.LoginLogMapper;
import org.example.system.service.LoginLogService;
import org.example.utils.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

/**
 * 登录日志服务层实现类
 */
@Service
public class LoginLogServiceImpl implements LoginLogService {

    @Autowired
    private LoginLogMapper loginLogMapper;

    /**
     * 添加登录日志
     * @param loginLog
     * @param request
     * @return
     */
    @Override
    public int add(LoginLog loginLog,HttpServletRequest request) {
        loginLog.setIpAddress(IpUtil.getIpAddr(request));
        try {
            loginLog.setAddress(IpUtil.getIpPossession(IpUtil.getIpAddr(request)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("user-agent"));
        loginLog.setBrowser(userAgent.getBrowser().toString());
        loginLog.setPlatform(userAgent.getOperatingSystem().getName());
        loginLog.setLogTime(new Date());
        return loginLogMapper.insert(loginLog);
    }

    /**
     * 按条件分页查询
     * @param loginLog
     * @return
     */
    @Override
    public IPage<LoginLog> selectPage(LoginLog loginLog){
        LambdaQueryWrapper<LoginLog> wrapper = new LambdaQueryWrapper<>();
        //条件
        if (StrUtil.isNotEmpty(loginLog.getIpAddress())){
            wrapper.like(LoginLog:: getIpAddress,loginLog.getIpAddress());    //相似的IP地址（模糊查询）
        }
        if (StrUtil.isNotEmpty(loginLog.getUsername())){
            wrapper.like(LoginLog:: getUsername,loginLog.getUsername());    //相似的用户名（模糊查询）
        }
        if (StrUtil.isNotEmpty(loginLog.getStatus())){
            wrapper.eq(LoginLog:: getStatus,loginLog.getStatus());    //相同的状态（精确查询）
        }
        wrapper.orderByDesc(LoginLog::getId);
        IPage<LoginLog> page = new Page<>();
        page.setCurrent(loginLog.getPageNum());
        page.setSize(loginLog.getPageSize());
        return loginLogMapper.selectPage(page,wrapper);
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @Override
    public int deleteBatch(Long[] ids) {
        return loginLogMapper.deleteBatchIds(Arrays.asList(ids));
    }
}
